<!doctype html>
<html class="no-js" lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta charset="utf-8">

    <title>Utbudstjänst - Användare</title>

    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">

    <link rel="stylesheet" href="../css/font-awesome.css">
    <link rel="stylesheet" href="../css/bootstrap.css">
    <link rel="stylesheet" href="../css/prism.css">
    <link rel="stylesheet" href="../css/chosen.min.css">
    <link rel="stylesheet" href="../css/bootstrap-responsive.css">
    <link rel="stylesheet" href="../css/datepicker.css">
    <link rel="stylesheet" href="../css/ui-lightness/jquery-ui-1.8.21.custom.css">
    <link rel="stylesheet" href="../css/jquery.dataTables.css">
    <link rel="stylesheet" href="../css/application-ocean-breeze.css">
    <link rel="stylesheet" href="../css/msgGrowl.css" type="text/css" charset="utf-8" />
    <link rel="stylesheet" href="../css/jquery.msgbox.css">

    <script src="../js/lib/modernizr-2.5.3.min.js"></script>

    <script id="detailTemplate" type="text/html">
        <h2 class="closeable unmodified"><i class="icon-check-minus"></i> <span id="edit-title">Ny användare</span></h2>

        <div class="row-fluid unmodified">
            <div class="alert">
                <strong>Du har osparade ändringar!</strong> För att stänga raden måste du <a class="action-save">spara</a> eller <a class="action-cancel">avbryta</a>.
            </div>
        </div>

        <div  class="row-fluid">
            <div id="create-user">
                <div class="span4">
                    <legend>Användardata</legend>

                    <div class="control-group">
                        <label>Användar-ID</label>
                        <div class="controls">
                            <input id="inputUsername" class="input-large" type="text" required disabled/>
                        </div>
                    </div>

                    <div class="control-group">
                        <label>Nytt lösenord</label>
                        <div class="controls">
                            <input id="inputPassword" class="input-large" type="text"/>
                        </div>
                    </div>

                    <div class="control-group">
                        <label>Bekräfta lösenord</label>
                        <div class="controls">
                            <input id="inputConfirmPassword" class="input-large" type="text"    />
                        </div>
                    </div>

                    <div class="control-group">
                        <label>Behörighet</label>
                        <div class="controls">
                            <select id="dropSetRole" class="chosen-select listen-change"></select>
                        </div>
                    </div>

                    <div class="control-group">
                        <label>Namn</label>
                        <div class="controls">
                            <input id="inputRealname" class="input-large" type="text"/>
                        </div>
                    </div>

                    <div class="control-group">
                        <label>E-post</label>
                        <div class="controls">
                            <input id="inputEmail" class="input-large" type="text"/>
                        </div>
                    </div>
                </div>

                <div class="span8 no-left-padding">
                    <div>
                        <legend>Utbudspunkter att administrera</legend>

                        <div class="control-group">
                            <table id="tableUnits" class="table">
                                <thead>
                                <tr>
                                    <th width="25%">HSA-ID</th>
                                    <th width="70%">Namn</th>
                                    <th width="5%"></th>
                                </tr>
                                </thead>
                                <tbody id="tableBodyUnits"></tbody>
                            </table>
                        </div>
                        <div class="control-group" id="dropUnits">
                            <select id="utbudspunkter"></select>
                            <button id="addUnit" class="btn pull-right listen-click" disabled="true"><i class="icon-plus"></i> Lägg till</button>
                        </div>
                    </div>
                </div>

                <!-- Actions Save & Cancel -->
                <div class="row-fluid actions-item">
                    <div class="span12 unmodified">
                        <div class="pull-right">
                            <a class="btn action-cancel"><i class="icon-remove"></i> Avbryt</a>
                            <a class="btn btn-primary action-save" disabled="disabled"><i class="icon-thumbs-up"></i> Spara</a>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        </div>
    </script>

</head>
<body>

<div id="wrapper">

    <div id="headerPlaceholder"></div>

    <div id="content">
        <div class="container">
            <div id="createPlaceholder" class="info_row hidden"></div>
            <div class="row">
                <div class="span12">
                    <div id="list">
                        <table id="masterTable" cellpadding="0" class="table table-striped table-condensed table-hover dataTable">
                            <thead>
                            <tr>
                                <th width="25%" class="header">Namn</th>
                                <th width="20%" class="header">Användar-ID</th>
                                <th width="20%" class="header">E-post</th>
                                <th width="15%" class="header">Behörighet</th>
                                <th width="10%" class="header">Senast uppdaterad</th>
                                <th width="10%" class="header">Senast inloggad</th>
                            </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div> <!-- /.span12 -->
            </div> <!-- /.row -->
        </div> <!-- /.container -->
    </div> <!-- /#content -->
</div> <!-- /#wrapper -->

<script src="../js/lib/jquery-1.7.2.min.js"></script>
<script src="../js/lib/jquery-ui-1.8.21.custom.min.js"></script>
<script src="../js/lib/jquery.ui.touch-punch.min.js"></script>
<script src="../js/lib/bootstrap.min.js"></script>
<script src="../js/lib/moment.min.js"></script>
<script src="../js/lib/jquery.tablesorter.min.js"></script>
<script src="../js/lib/jquery.dataTables.js"></script>
<script src="../js/lib/jquery.validate.js"></script>
<script src="../js/lib/chosen.jquery.min.js"></script>
<script src="../js/lib/msgGrowl.min.js"></script>
<script src="../js/lib/jquery.cookie.js"></script>
<script src="../js/lib/jquery-handlebars-1.1.4.min.js"></script>
<script src="../js/md.js"></script>
<script src="../js/common.js"></script>
<script>
        commonInit({
            tabUser: true,
            viewDataUrl: '../rest/view/users',
            mastheadTitle: 'Användare',
            mastheadSubtitle: 'Administration av användare',
            mastheadContent: '<a class="btn pull-right" onclick="$(\'#list\').MasterDetail(\'toggleCreateDetail\');"><i class="icon-plus"></i> Ny användare</a>'
        });

        $("#list").MasterDetail({
            masterData: viewData.users,
            masterColumns: [
                {
                    mData: 'realname',
                    mRender: MasterDetail.renderString
                }, {
                    mData: 'hsaId',
                    mRender: MasterDetail.renderString
                }, {
                    mData: 'email',
                    mRender: MasterDetail.renderString
                }, {
                    mData: 'role',
                    mRender: renderRole
                }, {
                    mData: 'updatedTime',
                    mRender: MasterDetail.renderDate
                }, {
                    mData: 'lastLogin',
                    mRender: MasterDetail.renderDate
                }
            ],
            initDetail: initDetail,
            createDetail: createDetail,
            updateDetail: updateDetail,
            validateDetail: validateDetail
        });

        function renderRole(data, type, full) {
            return MasterDetail.renderString(viewData.roles[data], type, full);
        }

        function initDetail(container, data) {
            $('#title', container).text(data ? 'Ändra användare' : 'Ny användare');

            var roleSelect = $('#dropSetRole', container);
            roleSelect.append('<option></option>');
            $.each(viewData.roles, function(key, val) {
                roleSelect.append('<option value="' + key + '">' + val + '</option>');
            });

            var unitSelect = $('#utbudspunkter', container);
            unitSelect.append('<option></option>');
            $.each(viewData.units, function(key, val) {
                if (val.displayName) {
                    unitSelect.append('<option value="' + val.hsaId + '">' + val.displayName + ' (' + val.hsaId + ')</option>');
                }
            });

            var careUnits = [];
            if (data) {
                $('#inputUsername', container).val(data.hsaId);
                $('#inputRealname', container).val(data.realname);
                $('#inputEmail', container).val(data.email);
                $('#edit-title', container).text(data.realname);
                $('#inputUsername', container).prop('disabled', true);
                roleSelect.val(data.role);
                careUnits = data.careUnits;
            } else {
                $('#inputUsername', container).prop('disabled', false);
            }

            var unitsTable = $('#tableUnits', container).dataTable({
                aoColumns: [
                    {mData: 'hsaId',
                        mRender: MasterDetail.renderString
                    },
                    {"mData": 'displayName',
                        mRender: MasterDetail.renderString
                    },
                    {sDefaultContent: '<a class="delete-unit"><i class="icon-trash listen-click"></i></a>',
                        bSortable: false,
                        bSearchable: false
                    }
                ],
                bDeferRender: true,
                bFilter: false,
                bDestroy: true,
                bSortCellsTop: true,
                bPaginate: false,
                bInfo: false,
                aaData: careUnits,
                fnCreatedRow: function(row, data, dataIndex) {
                    $('.delete-unit', row).click(function() {
                        unitsTable.fnDeleteRow(row);
                    });
                }
            });

            roleSelect.chosen({
                placeholder_text_single: 'Välj roll...',
                disable_search_treshold: 10
            });
            unitSelect.chosen({
                placeholder_text_single: 'Välj utbudspunkt...',
                disable_search_treshold: 10,
                width: '480px',
                search_contains: true
            });
            $('#addUnit', container).click(function() {
                addUnit(unitsTable, unitSelect);
                $('#addUnit', container).prop('disabled', true);
            });
            unitSelect.on('change', function(evt, params) {
                $('#addUnit', container).prop('disabled', false);
            });
        }

        function addUnit(table, select) {
            var hsaId = select.val();
            console.log('Add unit: hsaId=' + hsaId);
            // Avoid duplicates
            var existing = $.grep(table.fnGetData(), function(e) {
                return e.hsaId === hsaId;
            });
            if (existing.length === 0) {
                var unitData = $.grep(viewData.units, function(e) {
                    return e.hsaId === hsaId;
                });
                table.fnAddData({
                    hsaId: hsaId,
                    displayName: unitData[0].displayName
                });
            }
            // Reset selection
            select.chosen().val('');
            select.trigger('chosen:updated');
        }

        function createDetail(container) {
            $('#edit', container).validate({
                rules: {
                    inputEmail: "required",
                    inputPassword: "required",
                    inputConfirmPassword: {
                        equalTo: "#inputPassword"
                    }
                },
                messages: {
                    inputEmail: "E-postadress måste anges",
                    inputPassword: "Lösenord måste anges",
                    inputConfirmPassword: {
                        equalTo: "Lösenorden överensstämmer inte"
                    }
                }
            });

            var units = $('#tableUnits', container).dataTable().fnGetData();
            units = $.map(units, function(e) {
                return {
                    hsaId: e.hsaId
                };
            });
            data = {
                hsaId: $('#inputUsername', container).val(),
                realname: $('#inputRealname', container).val(),
                email: $('#inputEmail', container).val(),
                password: $('#inputPassword', container).val(),
                role: $('#dropSetRole', container).val(),
                status: 'ACTIVE',
                careUnitID: units
            };

            console.log("Creating data:");
            console.log(data);

            var retData = false;
            $.ajax({
                url: config.guiURL + '/users',
                type: 'POST',
                data: JSON.stringify(data),
                contentType: 'application/json; charset=UTF-8',
                dataType: 'json',
                async: false,
                success: function(data) {
                    showGrowlMessage('Användare skapad.');
                    retData = data;
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    showErrorGrowlMessage(jqXHR.responseText);
                }
            });
            return retData;
        }

        function updateDetail(container) {
            $('#edit', container).validate({
                rules: {
                    inputEmail: "required",
                    inputConfirmPassword: {
                        equalTo: "#inputPassword"
                    }
                },
                messages: {
                    inputEmail: "E-postadress måste anges",
                    inputConfirmPassword: {
                        equalTo: "Lösenorden överensstämmer inte"
                    }
                }
            });

            var passwordRaw = $('#inputPassword').val();
            var password = passwordRaw !== '' ? passwordRaw : null;

            var units = $('#tableUnits', container).dataTable().fnGetData();
            units = $.map(units, function(e) {
                return {
                    hsaId: e.hsaId
                };
            });
            data = {
                hsaId: $('#inputUsername', container).val(),
                realname: $('#inputRealname', container).val(),
                email: $('#inputEmail', container).val(),
                password: password,
                role: $('#dropSetRole', container).val(),
                status: 'ACTIVE',
                careUnitID: units
            };

            console.log("Updating data:");
            console.log(data);

            var retData = false;
            $.ajax({
                url: config.guiURL + '/users/' + data.hsaId,
                type: 'PUT',
                data: JSON.stringify(data),
                contentType: 'application/json; charset=UTF-8',
                dataType: 'json',
                async: false,
                success: function(data) {
                    showGrowlMessage('Användare uppdaterad.');
                    retData = data;
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    showErrorGrowlMessage(jqXHR.responseText);
                }
            });
            return retData;
        }

        /**
        * Validates form
        * 
        * @param {type} container
        * @returns {true or false}
        */
        function validateDetail(container) {
            return true;
        }
    </script>
</body>
</html>
